<?php
declare(strict_types=1);

namespace app\common\business;

use app\common\model\Attribute as AttributeModel;
use app\common\model\RelationAttributeCategory as RelationAttributeCategoryModel;
use app\common\model\Category as CategoryModel;
use Exception;

class Attribute extends CommonBase
{
    private $_attributeObj = null;

    public function __construct(string $websiteCode)
    {
        $this->_attributeObj = new AttributeModel([], $websiteCode);
        $this->_websiteCode  = $websiteCode;
    }

    public function getAllAttribute(array $where = []): array
    {
        $rows = [];
        try {
            $rows = $this->_attributeObj->getAllAttribute($where);
        } catch (Exception $e) {
            logErr('读取所有属性失败', sprintf('websiteCode:%s,method:%s,err:%s', $this->_websiteCode, __METHOD__, $e->getMessage()));
        }

        return $rows;
    }

    public function getAttributeList(int $page = 1, int $limit = 10, array $where = []): array
    {
        $res   = [];
        $count = 0;
        try {
            $res   = $this->_attributeObj->getAttributeList($page, $limit, $where);
            $count = $this->_attributeObj->getAttributeCount($where);
        } catch (Exception $e) {
            logErr('读取属性列表失败', sprintf('websiteCode:%s,method:%s,err:%s', $this->_websiteCode, __METHOD__, $e->getMessage()));
        }

        $rows = $res->toArray();

        foreach ($rows as $key => $row) {
            $rows[$key]['attribute_type_name'] = $row['attribute_type'] == 1 ? '普通' : '图片';
        }

        return ['rows' => $rows, 'count' => $count];
    }

    public function addAttribute(array $data): array
    {
        try {
            return [self::_RESULT => $this->_attributeObj->addAttribute($data), self::_MESSAGE => self::_ADD_SUCCESS_MESSAGE];
        } catch (Exception $e) {
            logErr('添加属性失败', sprintf('websiteCode:%s,method:%s,err:%s', $this->_websiteCode, __METHOD__, $e->getMessage()));
        }

        return [self::_RESULT => false, self::_MESSAGE => self::_SYSTEM_ERROR_MESSAGE];
    }

    public function findAttributeById(int $id): array
    {
        $attribute = [];
        try {
            $attribute = $this->_attributeObj->findAttributeById($id);
        } catch (Exception $e) {
            logErr('通过主键读取属性详细信息失败', sprintf('websiteCode:%s,method:%s,err:%s', $this->_websiteCode, __METHOD__, $e->getMessage()));
        }

        return $attribute;
    }

    public function updateAttribute(int $id, array $data): array
    {
        try {
            return [self::_RESULT => $this->_attributeObj->updateAttribute($id, $data), self::_MESSAGE => self::_UPDATE_SUCCESS_MESSAGE];
        } catch (Exception $e) {
            logErr('通过主键更新属性信息失败', sprintf('websiteCode:%s,method:%s,err:%s', $this->_websiteCode, __METHOD__, $e->getMessage()));
        }

        return [self::_RESULT => false, self::_MESSAGE => self::_SYSTEM_ERROR_MESSAGE];
    }

    public function deleteAttribute(int $id): array
    {
        try {
            $checkAttributeIsUsedRes = $this->_checkAttributeIsUsed($id);
            if ($checkAttributeIsUsedRes['used']) {
                return [self::_RESULT => false, self::_MESSAGE => $checkAttributeIsUsedRes[self::_MESSAGE]];
            }

            return [self::_RESULT => $this->_attributeObj->deleteAttribute($id), self::_MESSAGE => self::_DELETE_SUCCESS_MESSAGE];
        } catch (Exception $e) {
           logErr('通过主键删除属性失败', sprintf('websiteCode:%s,method:%s,err:%s', $this->_websiteCode, __METHOD__, $e->getMessage()));
        }

        return [self::_RESULT => false, self::_MESSAGE => self::_SYSTEM_ERROR_MESSAGE];
    }

    public function clearAttributeCache(): bool
    {
        return $this->_attributeObj->clearAttributeCache();
    }

    private function _checkAttributeIsUsed($id): array
    {
        $relationAttributeCategoryModel = new RelationAttributeCategoryModel([], $this->_websiteCode);
        $relationAttributeCategoryObj   = $relationAttributeCategoryModel->getAllRelationAttributeCategoryByAttributeId($id);
        $relationAttributeCategories    = $relationAttributeCategoryObj->toArray();
        if (empty($relationAttributeCategories)) {
            return ['used' => false, self::_MESSAGE => ''];
        }

        $categoryIds = [];
        foreach ($relationAttributeCategories as $category) {
            $categoryIds[] = $category['category_id'];
        }

        $categoryModel = new CategoryModel([], $this->_websiteCode);
        $categoryObj   = $categoryModel->getAllCategoryByIds($categoryIds);
        $categories    = $categoryObj->toArray();
        if (empty($categories)) {
            return ['used' => false, self::_MESSAGE => ''];
        }

        $categoryTitles = [];
        foreach ($categories as $key => $category) {
            if ($key >= 2) {
                break;
            }
            $categoryTitles[] = $category['title'];
        }

        $categoryTitle = implode(',', $categoryTitles);
        if (count($categoryTitles) > 1) {
            $categoryTitle .= '... 共' . count($categoryObj) . '个栏目';
        }

        return ['used' => true, self::_MESSAGE => sprintf(self::_DELETE_ATTRIBUTE_IS_USED_ERROR, $categoryTitle)];
    }
}
